<template>
  <el-form-item :label="props.title" :props="props.field" class="expand-form-item">
    <el-cascader v-model="selectVal" :options="treeData" :props="treeProps" separator=" > " popper-class="pid-cascader" placeholder="选择栏目"></el-cascader>
    <div v-if="props.children && props.children.length > 0" class="option-box">
      <div class="option-btn" @click="changeChildrenShow">
        <div class="option-btn-icon">
          <span :class="{ plus: childrenShow }"></span>
        </div>
        <p>{{ childrenShow ? "取消" : "拓展" }}</p>
      </div>
    </div>
  </el-form-item>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useStore } from 'vuex'
import { getAllCategory } from '@/api/category'

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  value: {
    type: Array,
    default: null
  },
  placeholder: {
    type: String,
    default: ''
  },
  children: {
    type: Array,
    default: () => []
  },
  childrenShow: {
    type: Boolean,
    default: false
  },
  setting: {
    type: Object,
    default: () => {}
  }
})
const emits = defineEmits(['update:value', 'update:childrenShow'])
const store = useStore()

const childrenShow = computed(() => props.childrenShow)
const changeChildrenShow = () => {
  emits('update:childrenShow', !childrenShow.value)
}
const selectVal = computed({
  get: () => (props.value ? props.value : []),
  set: val => {
    emits('update:value', val)
  }
})

const siteId = computed(() => store.state.site.currentSite?.id)
const treeData = ref([])
const treeProps = reactive({
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  expandTrigger: 'hover',
  emitPath: false,
})
const _getAllCategory = async () => {
  const res = await getAllCategory({siteId: siteId.value})
  if (res.code === 20000) {
    treeData.value = buildTree(res.data)
  }
}
_getAllCategory()
const buildTree = (array, rootId = 0) => {
  const tree = [{ id: 0, name: '根目录', children: [] }]
  const children = {}
  array.forEach(item => {
    children[item.id] = item
    if (item.pid === rootId) {
      tree.push(item)
    } else {
      const parent = children[item.pid]
      if (parent) {
        (parent.children = parent.children || []).push(item)
      }
    }
  })
  return tree
}
</script>

<style lang="scss" scoped>

</style>
